package com.github.zxhTom.demo.mina.client;

import com.github.zxhTom.demo.mina.Constaint;
import com.github.zxhTom.demo.mina.factory.SocketFactory;
import com.github.zxhTom.demo.mina.service.ServerMessageHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * 客户端
 */
public class Client {
    private static Logger logger = LogManager.getLogger(Client.class);

    public static void main(String[] args) {
        //创建监听对象
        IoConnector connector = new NioSocketConnector();
        TextLineCodecFactory textLineCodecFactory =
                new TextLineCodecFactory(Charset.forName("utf-8"), LineDelimiter.WINDOWS.getValue(),
                        LineDelimiter.WINDOWS.getValue());
        //添加过滤器
        connector.getFilterChain().addLast("logger",new LoggingFilter());
        connector.getFilterChain().addLast("protocal",new ProtocolCodecFilter(
                new SocketFactory()
        ));
        //设置时间处理的handler
        connector.setHandler(new ClientMessageHandler());
        //设置读取数据缓存区的大小
        connector.getSessionConfig().setReadBufferSize(Constaint.READSIZE);
        //设置多久没有消息就进入空闲状态
        connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE,Constaint.IDLETIME);
        ConnectFuture future = connector.connect(new InetSocketAddress(Constaint.REMOTE_IP,Constaint.REMOTE_PORT));
        future.addListener(new IoFutureListener<IoFuture>() {
            @Override
            public void operationComplete(IoFuture ioFuture) {
                logger.info("连接准备完成");
                IoSession session = ioFuture.getSession();

            }
        });
    }
}
